#!/usr/bin/env python
"""
signpkg

Takes a URL to a .ubiq file and requets the ubiq file be signed by an 
optionally specified signing server.  The output will be the signed ubiq file
which can then replace the originally signed ubiq file.

Example:  signpkg -f signed http://cct.lsu.edu/~mkemp2/libpng/v1_2_25.ubiq
"""

__author__ = 'Matt Kemp <mkemp2@cct.lsu.edu>'
__version__ = 'signpkg v0.1 6-13-08'

import sys
import urllib2
from urllib import urlencode
from optparse import OptionParser

def signpkg(ubiqfile, server):
    """Takes a url to a ubiq file and an signing server as input
    and returns the signed ubiq file.
    """

    try:
        response = urllib2.urlopen('%s/signpkg?url=%s' % (server, ubiqfile))
    except urllib2.URLError, e:
        if hasattr(e, 'reason'):
            return 'error: %s\n' % e.reason[1]
        elif hasattr(e, 'code'):
            return 'error %d: %s\n' % (e.code, e.read())
    else:
        return response.read()

if __name__ == '__main__':

    usage = 'usage: %prog [options] <url_to_ubiq_file>'
    parser = OptionParser(version=__version__)
    parser.set_usage(usage)
    parser.add_option('-f', '--file', dest='filename',
                      help='write output to FILE', metavar='FILE')
    parser.add_option('--server', dest='server',
                      help='alternate server used to sign .ubiq files',
                      default='http://pony.appspot.com')
            
    opts, args = parser.parse_args()
    if len(args) < 1:
        parser.error('requires one argument')

    if not opts.filename:
        outfile = sys.stdout
    else:
        outfile = open(opts.filename,'w')
    outfile.write(signpkg(args[0], opts.server))
    outfile.close()
